from __future__ import absolute_import
import logging
from forest.api import Command, get_tool
from os.path import join, exists

logger = logging.getLogger('commands.files.Append')

copy = get_tool('system.copy')

class Append(Command):
    ''' Appends lines to the specified file.

        Example::

            append:
              - file: /etc/fstab
                lines:
                - tmpfs /   tmpfs   defaults    0   0

        .. describe:: append[*].file

            The file name to append lines

        .. describe:: append[*].lines

            An array of strings representing lines to add.
    '''
    # TODO: only append lines if they are inside already
    __register__ = 'commands.files.Append'

    def run(self, config):
        install_tree = config.get_install_root()
        args = config.get('append', False)

        if not args:
            return

        print args
        for append in args:
            fulldestpath = [install_tree] + append.get('file').split('/')
            fulldestpath = join(*fulldestpath)

            Command.SIGNAL_COMMAND_PROGRESS(self, message='Appending to %s' % (fulldestpath))

            if exists(fulldestpath):
                # one pass to see what we need to append
                f = open(fulldestpath, 'r')
                data = f.read()
                f.close()

                lines_to_append = []
                for line in append.get('lines'):
                    if data.find(line) == -1:
                        lines_to_append.append(line)

                if not lines_to_append:
                    continue
            else:
                lines_to_append = append.get('lines')

            # actually write the lines_to_append
            f = open(fulldestpath, 'a')
            for line in lines_to_append:
                f.write('%s\n' % line)
            f.close()
